package com.hankol.community.viewmodel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import com.baselibrary.Constants
import com.baselibrary.base.BasicListBean
import com.baselibrary.activity.BaseActivity
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.*
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.setDefTTF
import com.baselibrary.manager.LoadingManager
import com.baselibrary.net.APIResponse
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.PopUtils
import com.baselibrary.utils.PosterStyle
import com.baselibrary.utils.ShareManager
import com.baselibrary.view.share.SharePopupWindow
import com.flyco.tablayout.SlidingTabLayout
import com.hankol.community.R
import com.hankol.community.SelectFriendShareActivity
import com.hankol.community.ShareFriendActivity
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.*
import com.hankol.community.databinding.PopupCommentlistBinding
import com.hankol.community.fragment.CommunityFollowFragment
import com.hankol.community.respository.CommunityRequestManager
import com.liaoinstan.springview.utils.DensityUtil
import com.okhttp.callbacks.GenericsCallback
import com.okhttp.comment.CommentBean
import com.okhttp.sample_okhttp.JsonGenericsSerializator
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import okhttp3.Call

/*社区接口*/
class CommunityViewModel : BaseViewModel() {
    var bannerAndHotTagsLD: MutableLiveData<HotBannerData.DataDTO> = MutableLiveData()
    var topicDetailLD: MutableLiveData<TopicDetailsBean.DataBean> = MutableLiveData()
    var channelListLD: MutableLiveData<List<HomeChannelBean>> = MutableLiveData()
    var wikiMld: MutableLiveData<List<WikiHomeAmusingMoreRespWiki.DataBean>> = MutableLiveData()

    var wikiBannerld: MutableLiveData<List<WikiHomeAmusingMoreRespWiki.DataBean>> = MutableLiveData()

    //专栏列表
    var columnListMld: MutableLiveData<BasicListBean<SquareSpecialColumnBean>> = MutableLiveData()

    //讲坛分类  分页列表
    var forumClassifyMld: MutableLiveData<BasicListBean<ForumClassifyListBean>> = MutableLiveData()

    //某个分类下 的 讲坛  分页列表
    var forumMld: MutableLiveData<BasicListBean<ForumListBean>> = MutableLiveData()

    //专栏列表
    var columnDetailMld: MutableLiveData<BasicListBean<ColumnDetailsListBean>> = MutableLiveData()
    var goodUserLD: MutableLiveData<GoodUserBean> = MutableLiveData()
    var followDynamicLD: MutableLiveData<FollowDynamicBean.DataBeanX> = MutableLiveData()
    var followUsersLD: MutableLiveData<FollowUserBean> = MutableLiveData()
    var followUsersAllLD: MutableLiveData<BasicListBean<FollowUsersBeanItem>> = MutableLiveData()
    var interestUsersLD: MutableLiveData<List<InterestUserBean>> = MutableLiveData()
    var recommendUsersLD: MutableLiveData<List<RecommendUserBean>> = MutableLiveData()
    var noCareLD: MutableLiveData<Boolean> = MutableLiveData()
    var articleDetailLD: MutableLiveData<ArticleDetailBean> = MutableLiveData()
    var articleDetailNumPlusLD: MutableLiveData<Boolean> = MutableLiveData()

    //专栏详情
    var columnDetailLD: MutableLiveData<ColumnDetailBean> = MutableLiveData()

    //讲坛分类 详情
    var forumClassDetailLD: MutableLiveData<ForumClassifyInfoBean> = MutableLiveData()
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()
    //话题分类列表
    var topicTagListLD: MutableLiveData<List<TopicClassifyBean>> = MutableLiveData()
    var searchTopicLD: MutableLiveData<List<SearchTopicBean>> = MutableLiveData()

    var homePageLd: MutableLiveData<HomePageBean> = MutableLiveData()


    /**
     *  首页Banner和热门话题
     */
    fun requestBannerAndHotTags() {
        CommunityRequestManager.getInstance().requestBannerAndHotTags(bannerAndHotTagsLD)
    }

    /**
     *  频道Banner和热门话题
     */
    fun requestChannelBannerAndHotTags(channelId: Int) {
        CommunityRequestManager.getInstance().requestChannelBannerAndHotTags(channelId, bannerAndHotTagsLD)
    }


    /**
     *  话题详情页
     */
    fun requestTopicDetail(id: String) {
        CommunityRequestManager.getInstance().requestTopicDetail(id, topicDetailLD)
    }

    /**
     *  话题详情页活跃优质用户列表
     */
    fun requestTopicGoodUser(page: Int, id: String) {
        CommunityRequestManager.getInstance().requestTopicGoodUser(page, id, goodUserLD)
    }

    /**
     *  直播预约
     */
    fun requestSubscribeLive(context: Context, hasSubscribe: Boolean, id: String, apiResponse: APIResponse<String>) {
        if (hasSubscribe) {
            PopUtils.showOkCancelDialog(context as Activity, "确认取消预约？", object : PopUtils.ICallBack {
                override fun clickOk() {
                    CommunityRequestManager.getInstance().requestCancelSubscribeLive(id, apiResponse)
                }

                override fun clickCancel() {

                }

            }, false, "确认", "取消")
        } else {
            CommunityRequestManager.getInstance().requestSubscribeLive(id, apiResponse)
        }
    }


    /**
     *  首页频道列表
     */
    fun requestChannelList() {
        CommunityRequestManager.getInstance().requestChannelList(channelListLD)
    }

    /**
     * 专栏列表
     */
    fun reqColumnListData(page: Int) {
        CommunityRequestManager.getInstance().reqColumnListData(page, columnListMld)
    }


    /**
     * 百科分页列表
     */
    fun reqWikiList(page: Int) {
        CommunityRequestManager.getInstance().reqWikiList(page, object : GenericsCallback<WikiHomeAmusingMoreRespWiki>(JsonGenericsSerializator()) {
            override fun onError(call: Call?, e: Exception?, id: Int) {
                wikiMld.value = null
            }

            override fun onResponse(response: WikiHomeAmusingMoreRespWiki?, id: Int) {
                if (null == response || null == response.data) return
                wikiMld.value = response.data
            }
        })
    }

    /**
     * 百科Banner
     */
    fun reqWikiBanner() {
        CommunityRequestManager.getInstance().reqWikiBanner(object : GenericsCallback<WikiHomeAmusingMoreRespWiki>(JsonGenericsSerializator()) {
            override fun onError(call: Call?, e: Exception?, id: Int) {
                wikiBannerld.value = null
            }

            override fun onResponse(response: WikiHomeAmusingMoreRespWiki?, id: Int) {
                if (null == response || null == response.data) return
                wikiBannerld.value = response.data
            }
        })
    }

    /**
     * 讲坛分类  分页列表
     */
    fun reqForumClassifyList(page: Int) {
        CommunityRequestManager.getInstance().reqForumClassifyList(page, forumClassifyMld)
    }

    /**
     *某个分类下 的 讲坛  分页列表
     */
    fun reqForumList(ctId: Int, page: Int) {
        CommunityRequestManager.getInstance().reqForumList(ctId, page, forumMld)
    }


    /**
     * 专栏  分页列表
     */
    fun reqColumnDetailList(page: Int, cid: Int) {
        CommunityRequestManager.getInstance().reqColumnDetailList(page, cid, columnDetailMld)
    }

    /**
     * 关注页面动态列表
     */
    fun reqFollowDynamicList(page: Int) {
        CommunityRequestManager.getInstance().reqFollowDynamicList(page, followDynamicLD)
    }

    /**
     * 文章详情
     */
    fun reqArticleDetail(aid: Long) {
        CommunityRequestManager.getInstance().reqArticleDetail(aid, articleDetailLD)
    }

    /**
     * 文章详情 阅读数+1
     */
    fun reqArticleDetailRedNumPlus(aid: Long) {
        CommunityRequestManager.getInstance().reqArticleDetailRedNumPlus(aid, articleDetailNumPlusLD)
    }


    /**
     * 专栏详情
     */
    fun reqColumnDetailData(aid: Int) {
        CommunityRequestManager.getInstance().reqColumnDetailData(aid, columnDetailLD)
    }

    /**
     *讲坛分类 详情
     */
    fun reqForumClassDetail(aid: Int) {
        CommunityRequestManager.getInstance().reqForumClassDetail(aid, forumClassDetailLD)
    }

    /**
     * 文章详情-评论
     */
    fun reqCommentList(page: Int, pictureId: Long, topCommentId: Long, type: Int) {
        CommunityRequestManager.getInstance().reqCommentList(commentListLiveData, page, type, pictureId, 0, topCommentId)
    }

    fun showShare(data: ShowShare2Bean, activity: BaseActivity, communityHelp: CommunityHelp,isShowReport:Boolean=true,isShowPrivateLetter:Boolean=true): SharePopupWindow? {
        val url: String = data.url
        val title = if (data.content.checkNotNull()) data.content else "@${data.name}发了一个动态，快点开来看看！"
        val des = if (data.content.checkNotNull()) data.content else ""
        val shareItem = ShareManager.showSharePopWindow(activity, url, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {

            override fun onShareClick(type: Int) {
                when (type) {
                    ShareItemBean.DOWN -> {

                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                val bundle1 = Bundle()
                                bundle1.putSerializable(Constants.SHARE_POSTER_BEAN, changePosterBean(data))
                                ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER, bundle1)
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        val intent = Intent()
                        val bundle = Bundle()
                        bundle.putInt("type", 3)
                        bundle.putInt("id", data.id.toInt())
                        bundle.putInt("complaintUserId", data.uid.toInt())
                        intent.putExtras(bundle)
                        activity.openActivity(communityHelp.getJuBaoOneActivity(), bundle)

                    }
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {//私信
                    //                        ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_SELECTED_FRIEND)
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }
            }
        })
        shareItem?.setShareItem(isShowPrivateLetter,false, false, isShowReport);
        return shareItem
    }

    fun changePosterBean(data: ShowShare2Bean): SharePosterBean {
        val sharePosterBean = SharePosterBean(2)
        sharePosterBean.userAvatar = data.headUrl
        sharePosterBean.userName = data.name
        sharePosterBean.shareImage = data.cover
        sharePosterBean.shareContent = data.content
        sharePosterBean.atPersonName = null
        sharePosterBean.isVideo = data.showType == 2
        sharePosterBean.isFans = data.isFans == 1
        return sharePosterBean
    }
    fun changePosterBean(data: FollowDynamicBean.DataBeanX.DataBean): SharePosterBean {
        val sharePosterBean = SharePosterBean(2)
        sharePosterBean.userAvatar = data.icon
        sharePosterBean.userName = data.name
        sharePosterBean.shareImage = data.cover
        sharePosterBean.shareContent = data.content
        sharePosterBean.atPersonName = getStrAt4New(data.atMembers);
        sharePosterBean.isVideo = data.showType == 2
        sharePosterBean.isFans = data.isFans == 1
        return sharePosterBean
    }
    fun getStrAt4New(atMembers: List<FollowDynamicBean.DataBeanX.DataBean.AtMembersBean>?): String? {
        if (atMembers == null || atMembers.size == 0) return ""
        val mBuffer = StringBuffer()
        for (atMember in atMembers) {
            mBuffer.append("@" + atMember.name).append("  ")
        }
        return mBuffer.toString()
    }
    /**
     * 将艾特的人名拼接成字符串
     */
    fun getStrAt(atMembers: List<TimelineInfoData.AtMembersBean>): String {
        if (atMembers.isEmpty()) return ""
        val mBuffer = StringBuffer()
        for (atMember in atMembers) {
            mBuffer.append("@" + atMember.name).append("  ")
        }
        return mBuffer.toString()
    }


    /**
     * 关注页面已关注人列表
     */
    fun reqFollowList() {
        CommunityRequestManager.getInstance().reqFollowList(followUsersLD)
    }

    /**
     * 关注页面已关注人列表
     */
    fun reqFollowListAll(page: Int) {
        CommunityRequestManager.getInstance().reqAllFollowList(followUsersAllLD, page)
    }

    /**
     * 有关注用户，推荐列表。你可能感兴趣的人top10
     */
    fun reqInterestUsers() {
        CommunityRequestManager.getInstance().reqInterestUsers(interestUsersLD)
    }

    /**
     * 还没有关注任何人时的推荐列表
     * @param index 第一次传 1 从第一个开始
     * @param size 第一次传 50 第五十个结束
     * 点击【X】不再推荐该用户后传以下
     * @param index 第一次传 1 从第一个开始
     * @param size 第一次传 50 第五十个结束
     */
    fun reqRecommendUsers(index: Int, size: Int) {
        CommunityRequestManager.getInstance().reqRecommendUsers(index, size, recommendUsersLD)
    }

    /**
     * 添加不在关注的人
     */
    fun reqNoCare(userId: Int) {
        CommunityRequestManager.getInstance().reqNoCardUser(userId, noCareLD)
    }

    fun followAction(activity: Activity, action: Boolean, id: Long, apiResponse: APIResponse<String>) {
        if (action) {
            CommunityRequestManager.getInstance().reqAddFollow(id, apiResponse)
        } else {
            PopUtils.showCancelFollow(activity, object : PopUtils.ICallBack {
                override fun clickOk() {
                    CommunityRequestManager.getInstance().reqCancelFollow(id, apiResponse)
                }

                override fun clickCancel() {

                }

            })
        }
    }

    /**关注  返回好友关系
     * @author: merbng
     * @time: 2022/5/31 14:43
     * @description:
     */
    fun followAction2(activity: Activity, action: Boolean, id: Long, apiResponse: APIResponse<FollowSuccBean>) {
        if (action) {
            CommunityRequestManager.getInstance().reqAddFollow2(id, apiResponse)
        } else {
            PopUtils.showCancelFollow(activity, object : PopUtils.ICallBack {
                override fun clickOk() {
                    CommunityRequestManager.getInstance().reqCancelFollow2(id, apiResponse)
                }

                override fun clickCancel() {

                }

            })
        }
    }

    fun likeAction(action: Boolean, id: Int, apiResponse: APIResponse<Boolean>) {
        if (action) {
            CommunityRequestManager.getInstance().reqAddLike(id, 4, apiResponse)
        } else {
            CommunityRequestManager.getInstance().reqCancelLike(id, 4, apiResponse)
        }
    }

    fun collectAction(action: Boolean, id: Long, apiResponse: APIResponse<Boolean>) {
        if (action) {
            CommunityRequestManager.getInstance().reqAddCollect(id, 4, apiResponse)
        } else {
            CommunityRequestManager.getInstance().reqCancelCollect(id, 4, apiResponse)
        }
    }


    fun openCommentView(f: CommunityFollowFragment, count: Int): PopupCommentlistBinding {
        val mPopupBinding = DataBindingUtil.bind<PopupCommentlistBinding>(LayoutInflater.from(f.context).inflate(R.layout.popup_commentlist, null))
        mPopupBinding!!.tvPopupContent.setOnClickListener(f)
        mPopupBinding.tvPopupSend.setOnClickListener(f)
        mPopupBinding.rlHeadLayout.visibility = View.VISIBLE
        mPopupBinding.ivClosePop.setOnClickListener(f)
        mPopupBinding.tvContentCount.text = "共${count}条评论"
        f.activity?.let { openComment(it, mPopupBinding, f) }
        mPopupBinding.BaseCommentView.setEmptyViewListener(f)
        return mPopupBinding
    }

    fun openComment(activity: Activity, mPopupBinding: PopupCommentlistBinding, listener: OnRefreshLoadMoreListener) {
        //弹窗Popup
        val mSpringPopup: SmartRefreshLayout = mPopupBinding.smartComment

        val linearParams = mPopupBinding.BaseCommentView.layoutParams as LinearLayout.LayoutParams
        linearParams.height = cutHeight(activity)
        mPopupBinding.BaseCommentView.layoutParams = linearParams
        mPopupBinding.BaseCommentView.setEmptyImgSize(DensityUtil.dip2px(activity, 200f), DensityUtil.dip2px(activity, 200f))
        mSpringPopup.setOnRefreshLoadMoreListener(listener)
        mPopupBinding.BaseCommentView.setAdapter(activity, null)

        mPopupBinding.BaseCommentView.visibility = View.GONE
        mPopupBinding.PBarSldComment.visibility = View.VISIBLE

    }

    fun cutHeight(context: Context): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm)
        val mScreenHeight = dm.heightPixels // 屏幕高度（像素）z
        return mScreenHeight / 2
    }

    /**
     * @param selectedTab 选中的tab下标
     */
    fun upTab(context: Context, tab: SlidingTabLayout, selectedTab: Int) {
        val tabCount = tab.tabCount
        for (pos in 0 until tabCount) {
            val tabTv = tab.getTitleView(pos)
            if (selectedTab == pos) {
                tabTv.setDefTTF(context)
            } else {
                tabTv.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
    }

    fun showShare(dynamicData: FollowDynamicBean.DataBeanX.DataBean, activity: Activity, communityHelp: CommunityHelp,list: MutableList<ShareItemBean>): SharePopupWindow? {
        val data = pulCourseBean2showShare(dynamicData)
        val title = if (data.content.checkNotNull()) data.content else "@${data.name}发了一个动态，快点开来看看！"
        val des = if (data.content.checkNotNull()) data.content else ""
        val shareItem = ShareManager.showSharePopWindow(activity, data.url, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {

            override fun onShareClick(type: Int) {
                when (type) {
                    ShareItemBean.WXZone, ShareItemBean.WX -> {
                        reqAddShareNum(dynamicData.id.toLong())
                    }
                    ShareItemBean.DOWN -> {

                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                LoadingManager.showLoadingDialog(activity)
                                var sharePosterBean: SharePosterBean = changePosterBean(dynamicData)
                                sharePosterBean.imagePaths = ArrayList()
                                for (i in 0..2) {
                                    val posterStyle = PosterStyle(activity, sharePosterBean, i) { path: String? ->
                                        sharePosterBean.imagePaths.add(path)
                                        checkListSize(activity, sharePosterBean)
                                    }
                                    posterStyle.startDraw()
                                }
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        val intent = Intent()
                        val bundle = Bundle()
                        bundle.putInt("type", 3)
                        bundle.putInt("id", data.id.toInt())
                        bundle.putInt("complaintUserId", data.uid.toInt())
                        intent.putExtras(bundle)
                        activity.startActivity(Intent(activity,communityHelp.getJuBaoOneActivity()), bundle)

                    }
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {//私信
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }

            }
        })?.setShareFriendAdapter(list)
        shareItem?.setShareItem(true, false, true);
        return shareItem
    }

    fun checkListSize(activity: Activity, sharePosterBean: SharePosterBean) {
        if (sharePosterBean.imagePaths.size == 3) {
            LoadingManager.hideLoadingDialog(activity)
            val bundle = Bundle()
            bundle.putSerializable(Constants.SHARE_POSTER_BEAN, sharePosterBean)
            ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER_SELECT, bundle)
        }
    }

    fun pulCourseBean2showShare(bean: FollowDynamicBean.DataBeanX.DataBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id.toLong()
            uid = bean.uid
            isFans = bean.isFans
            headUrl = bean.icon
            showType = Constants.DYNAMIC_TYPE_IMG
            name = bean.name
            cover = bean.cover
            title = bean.content
            content = bean.content
            url = Constants.DYNAMIC_SHARE_URL + bean.id
        }
    }

    /**
     * 话题分类列表
     * type 0选择话题 1全部话题
     */
    fun requestTopicTagList(type: Int) {
        CommunityRequestManager.getInstance().requestTopicTagList(type,topicTagListLD)
    }

    /**
     * 根据话题名搜索话题
     */
    fun requestSearchTopicByName(searchKey:String,type:Int) {
        CommunityRequestManager.getInstance().requestSearchTopicByName(searchKey,type,searchTopicLD)
    }

    /**
     * 首页改版接口
     */
    fun requestHomepageData() {
        CommunityRequestManager.getInstance().requestHomepageData(homePageLd)
    }

}